package com.xinhe.cn.cpbox.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinhe.cn.cpbox.common.Result;
import com.xinhe.cn.cpbox.service.ScripService;
import com.xinhe.cn.cpbox.entity.po.ScripGet;
import com.xinhe.cn.cpbox.entity.po.ScripSend;
import com.xinhe.cn.cpbox.mapper.ScripGetMapper;
import com.xinhe.cn.cpbox.mapper.ScripSendMapper;
import com.xinhe.cn.cpbox.payutils.WXPayParms;
import com.xinhe.cn.cpbox.utils.FileUtil;
import com.xinhe.cn.cpbox.utils.TencenCloudUtil;
import com.xinhe.cn.cpbox.utils.WechatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author HB
 * @date 2021/10/09 15:13
 */
@Slf4j
@Service
public class ScripServiceImpl implements ScripService {
    @Autowired
    TencenCloudUtil tencenCloudUtil;
    @Autowired
    ScripSendMapper scripSendMapper;
    @Autowired
    ScripGetMapper scripGetMapper;

    @Override
    public Object uploadImage(MultipartFile file) {
        // 腾讯云
        if (Objects.isNull(file)) {
            return Result.paramError();
        }
        //将MultipartFile转为文件
        try {
            File imageFile = FileUtil.byteToFile(file.getBytes(), file.getOriginalFilename());
            //将头像存储到对象桶
            String imageUrl = tencenCloudUtil.upload(imageFile);
            return Result.ok().message("保存成功").data("imageUrl", imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }

    @Override
    public Object checkMsg(String content) {
        if (org.springframework.util.StringUtils.isEmpty(content)) {
            return Result.ok();
        }

        String access_token = WechatUtil.getAccessToken(WXPayParms.PUBLIC_APPID, WXPayParms.PUBLC_SECRET);
        if (org.apache.commons.lang3.StringUtils.isEmpty(access_token)) {
            return Result.error().message("获取accessToken失败");
        }

        JSONObject object = new JSONObject();
        object.put("content", content);
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + access_token;
        String s = HttpRequest.post(url).body(object.toJSONString()).execute().body();
        return JSONObject.parse(s);
    }

    @Override
    public Object checkImg(MultipartFile file) throws Exception {
        if (Objects.isNull(file)) {
            return Result.paramError().message("文件为空！！");
        }
        // 获取accessToken
        String access_token = WechatUtil.getAccessToken(WXPayParms.PUBLIC_APPID, WXPayParms.PUBLC_SECRET);
        if (org.apache.commons.lang3.StringUtils.isEmpty(access_token)) {
            return Result.error().message("获取accessToken失败");
        }
        HashMap<String, Object> paramMap = new HashMap<>();
        File toFile = FileUtil.byteToFile(file.getBytes(), file.getOriginalFilename());
        paramMap.put("file", toFile);
        String url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + access_token;
        String result = HttpRequest.post(url).form(paramMap).execute().body();
        toFile.delete();
        return JSONObject.parseObject(result);
    }

    @Override
    public Object deleteScrip(ScripSend scripSend) {
        if (Objects.isNull(scripSend) || scripSend.getScripId() == 0) {
            return Result.paramError();
        }
        scripSendMapper.deleteById(scripSend);

        QueryWrapper<ScripGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scrip_id", scripSend.getScripId());
        scripGetMapper.delete(queryWrapper);
        return Result.ok();
    }

    @Override
    public Object findCanFreeSend(String type, String sendId) {
        if (StringUtils.isBlank(type) || StringUtils.isBlank(sendId)) {
            return Result.paramError();
        }

        Integer i = scripSendMapper.findCanFreeGet(type, sendId);
        return Result.ok().data("canFree", Objects.isNull(i));
    }

    @Override
    public Object sendScrip(ScripSend scripSend) {
        if (StringUtils.isBlank(scripSend.getType()) ||
                StringUtils.isBlank(scripSend.getContent()) ||
                StringUtils.isBlank(scripSend.getPicUrl()) ||
                StringUtils.isBlank(scripSend.getSendId())) {
            return Result.paramError();
        }

        // 审核状态
        scripSend.setChecked("0");

        if (Objects.isNull(scripSend.getScripId())) {
            scripSend.setSendTime(DateUtil.now());
            scripSend.setGetNum(0);
            scripSendMapper.insert(scripSend);
        } else {
            // 清除拒绝原因
            scripSend.setRejectReason(null);
            scripSendMapper.updateById(scripSend);
        }

        return Result.ok();
    }

    @Override
    public Object findCanGetScrip(String type, String getUserId) {
        if (StringUtils.isBlank(type) || StringUtils.isBlank(getUserId)) {
            return Result.paramError();
        }

        Integer i = scripSendMapper.findCanGetScrip(type, getUserId);
        return Result.ok().data("canGetScrip", !Objects.isNull(i));
    }

    @Override
    public Object getRandomScrip(String type, String getUserId) {
        if (StringUtils.isBlank(type) || StringUtils.isBlank(getUserId)) {
            return Result.paramError();
        }

        // 抽取一条纸条
        Long scripId = scripSendMapper.getRandomScrip(type, getUserId);
        if (!Objects.isNull(scripId)) {
            // 增加抽纸条记录
            ScripGet scripGet = new ScripGet();
            scripGet.setGetTime(DateUtil.now());
            scripGet.setGetUserId(getUserId);
            scripGet.setType(type);
            scripGet.setScripId(scripId);
            scripGetMapper.insert(scripGet);

            // 增加该纸条被抽到的次数
            scripSendMapper.addGetNum(scripId, 1);

            return Result.ok();
        } else {
            return Result.error().message("抽完了哦，歇一歇吧");
        }
    }

    @Override
    public Object getMyScripSend(String sendId, int page, int size) {
        if (StringUtils.isBlank(sendId) || page < 0 || size <= 0) {
            return Result.paramError();
        }

        // 查询条件
        QueryWrapper<ScripSend> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("send_id", sendId).eq("deleted", "0").orderByDesc("send_time");

        // 分页
        Page<ScripSend> mpPage = new Page<>(page, size);

        // 查询
        IPage<ScripSend> iPage = scripSendMapper.selectPage(mpPage, queryWrapper);

        // 返回总页数和数据
        return Result.ok().data("totalPage", iPage.getPages()).data("scripSendList", iPage.getRecords());
    }

    @Override
    public Object getMyScripGet(String getUserId, int page, int size) {
        if (StringUtils.isBlank(getUserId) || page < 0 || size <= 0) {
            return Result.paramError();
        }

        // 查询条件
        QueryWrapper<ScripSend> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sg.get_user_id", getUserId).eq("ss.checked", "1").orderByDesc("sg.get_time");

        // 分页
        Page<ScripSend> mpPage = new Page<>(page, size);

        // 查询
        IPage<ScripSend> iPage = scripGetMapper.getMyScripGet(queryWrapper, mpPage);

        // 返回总页数和数据
        return Result.ok().data("totalPage", iPage.getPages()).data("scripGetList", iPage.getRecords());
    }
}
